package com.ztom.daily.n2022.m3;

import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

/**
 * 根据二叉树创建字符串
 * <p>
 * https://leetcode-cn.com/problems/construct-string-from-binary-tree/
 *
 * @author ZhangTao
 */
public class Day19Tree2str {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 递归
     *
     * @param root
     * @return
     */
    public String tree2str1(TreeNode root) {
        if (root == null) {
            return "";
        }

        if (root.left == null && root.right == null) {
            return String.valueOf(root.val);
        }

        // 右节点为空, 可以省略()
        if (root.right == null) {
            return "" + root.val + "(" + tree2str(root.left) + ")";
        }
        return "" + root.val + "(" + tree2str(root.left) + ")(" + tree2str(root.right) + ")";
    }

    /**
     * 迭代
     *
     * @param root
     * @return
     */
    public String tree2str(TreeNode root) {
        if (root == null) {
            return "";
        }

        Deque<TreeNode> stack = new LinkedList<>();
        stack.offerLast(root);

        TreeNode cur = null;
        StringBuilder builder = new StringBuilder();
        Set<TreeNode> visited = new HashSet<>();
        while (!stack.isEmpty()) {
            cur = stack.peekLast();
            if (visited.contains(cur)) {
                if (cur != root) {
                    builder.append(")");
                }
                stack.pollLast();
            } else {
                visited.add(cur);
                if (cur != root) {
                    builder.append("(");
                }

                builder.append(cur.val);
                if (cur.left == null && cur.right != null) {
                    builder.append("()");
                }
                if (cur.right != null) {
                    stack.offerLast(cur.right);
                }
                if (cur.left != null) {
                    stack.offerLast(cur.left);
                }
            }
        }

        return builder.toString();
    }
}
